﻿using System;
using System.Threading.Tasks;
using Opc.Ua;
using Opc.Ua.Client;
using OpcUaHelper;


/***************************************************************************************************************
 * 
 * 
 * 
 * 
 * 
 * 
 *****************************************************************************************************************/


namespace OpcUaHelper.NetCoreDemo
{
    class Program
    {
        static async Task Main(string[] args)
        {
            OpcUaClient opcUaClient = new OpcUaClient("libai","123");

            try
            {
              await opcUaClient.ConnectServer("opc.tcp://47.94.135.225:49320");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Connect failed : " + ex.Message);
                return;
            }

            opcUaClient.WriteNode("ns=2;s=通道 1.设备 1.标记 1", (UInt16) 33);
            DataValue val = opcUaClient.ReadNode("ns=2;s=通道 1.设备 1.标记 1");

            UInt16 value = opcUaClient.ReadNode<UInt16>("ns=2;s=通道 1.设备 1.标记 1");
            opcUaClient.AddSubscription("1abc", "ns=2;s=通道 1.设备 1.标记 1", CallBack);
            opcUaClient.AddSubscription("2abc", "ns=2;s=通道 1.设备 1.标记 1", CallBack);
            opcUaClient.RemoveSubscription("ns=2;s=通道 1.设备 1.标记 3");
            opcUaClient.RemoveSubscription("ns=2;s=通道 1.设备 1.标记 5");

            opcUaClient.RemoveAllSubscription();
            opcUaClient.AddSubscription("3abc", new[] { "ns=2;s=通道 1.设备 1.标记 1", "ns=2;s=模拟器示例.函数.Ramp1" }, CallBack
                );
            //Console.WriteLine("ns=2;s=Machines/Machine B/TestValueFloat" + "   value: " + value);

            Console.WriteLine("Please enter any key to quit!");
            Console.ReadLine();
            opcUaClient.Disconnect();
        }

        private static int i = 0;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="arg1">订阅组名称</param>
        /// <param name="arg2">回调变量信息</param>
        /// <param name="arg3">订阅组变量值等</param>
        private static void CallBack(string arg1, MonitoredItem arg2, MonitoredItemNotificationEventArgs arg3)
        {
            i++;
            if (i % 10 != 0 && i % 10 != 1)
            {
                return;
            }
            var item = arg3.NotificationValue as MonitoredItemNotification;
            Console.WriteLine(item.Value.Value);
            Console.WriteLine(item.Value.WrappedValue + "******" + item.Value.StatusCode);
        }
    }
}
